<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Checkout extends MY_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
    
   
   
    public function __construct()
    {
        parent::__construct();
            // Your own constructor code
       $this->load->helper('https_helper');
       //use_ssl();
       use_ssl(FALSE);            
       
    } 
	public function index()
	{      
       $this->adres_bilgileri();
	}
    public function adres_bilgileri()
    {
      
           
            $data['profile_yazisi'] = "adres bilgilerim ";
            $data['subview'] = 'checkout/adres_bilgileri';
            
            $this->load->view('layouts/default1',$data);
    }
    public function talepler()
    {
      /*  echo "<pre>";
            var_dump($this->session->userdata('talepler_hemenal'));
            echo "</pre>";
            die();  */
       //$this->session->unset_userdata('cart_id');     
       $cart = array(
            'customer_id'   =>  $this->session->userdata('user_id'),
            'delivery_option'   =>  'test',
            'date_add'       =>  date("Y-m-d H:i:s"),
            'date_upd'       =>  date("Y-m-d H:i:s"),
            'status'         => 3
         );  
          if($this->db->insert('cart',$cart))
          {
             $cart_id = $this->db->insert_id();
             foreach($this->session->userdata('talepler_hemenal') as $products)
             {
                 $product_id = $this->db->where('seller_id',$products['seller_id'])->get('seller')->row(0)->product_id;
                              $cart_product = array(
                    'cart_id'       =>  $cart_id,
                    'product_id'    =>  $product_id,
                    'seller_id'     =>  $products['seller_id'],
                    'quantitiy'     =>  $products['adet'],
                    'attributes'    =>  3,
                    'module'        =>  5
                    
                 );
                 if($this->db->insert('cart_products',$cart_product))
                 {
                    
                    $this->session->set_userdata('talepler_hemenal',$cart_id);
                    
                        
                 }  
                 else
                 {
                    echo $this->db->_error_message()."<br>";
                     die('cart_prorducts tablosuna veri eklenemedi');
                 }
             }
          /*    echo "<pre>";
        print_r($this->session->userdata);
        die(); */
             /*   $cart_info = $this->sepetim_model->get_cart_products($cart_id);
               $this->session->set_userdata('products',$cart_info['products'] );
               $this->session->set_userdata('items',$cart_info['items']);
               $this->session->set_userdata('cart_id',$cart_info['cart_id']);
               $this->session->set_userdata('total',$cart_info['total']);*/
               
                $this->adres_bilgileri();

          }
          else
          {
                 echo $this->db->_error_message()."<br>";
                 die('cart tablosuna veri eklenemedi');
          }             
    }
    public function hizli_al()
    {
     
    /* echo "<pre>";
     print_r($this->input->post());
     die();*/
         $cart = array(
            'customer_id'   =>  $this->session->userdata('user_id'),
            'delivery_option'   =>  'test',
            'date_add'       =>  date("Y-m-d H:i:s"),
            'date_upd'       =>  date("Y-m-d H:i:s")
         );  
          if($this->db->insert('cart',$cart))
          {
             $cart_id = $this->db->insert_id();
             $cart_product = array(
                'cart_id'       =>  $cart_id,
                'product_id'    =>  $this->input->post('product_id'),
                'seller_id'     =>  $this->input->post('seller_id'),
                'quantitiy'     =>  $this->input->post('adet'),
                'attributes'    =>  3,
                'module'        =>  5
             );
             if($this->db->insert('cart_products',$cart_product))
             {
                    $this->session->set_userdata('talepler_hemenal',$cart_id);
                    //echo $cart_id."<br>";
                    
                    //die();
                    $this->adres_bilgileri();
             }  
             else
             {
                echo $this->db->_error_message()."<br>";
                 die('cart_prorducts tablosuna veri eklenemedi');
             }
          }
          else
          {
                 echo $this->db->_error_message()."<br>";
                 die('cart tablosuna veri eklenemedi');
          } 
    }
    public function odeme_bilgileri()
    {
         
        
            $this->session->set_userdata('checkout_adres_id',$this->input->post('adres_id'));
            $data['profile_yazisi'] = "odeme bilgilerim ";
            $data['subview'] = 'checkout/odeme_bilgileri';
            $this->load->view('layouts/default1',$data);        
    }
    public function alisveris_ozeti()
    {
       
            $data['invoice_id'] = $this->session->userdata('invoice');
            $payment_info = $this->db->where('invoice_id',$data['invoice_id'])->get('payment');
            if($payment_info->num_rows() > 0)
            {
                $payment_info = $payment_info->row(0);
           
                $cart_id = $payment_info->cart_id;
                $payment_type = $payment_info->type;
                $data['payment_type'] = $payment_type;
                $data['products'] = $this->product_model->get_cart_id_products($cart_id);    
                $data['adres_bilgileri'] = $this->db->where('adres_id',$payment_info->adres_id)->get('user_adres')->row(0);
            }

            $data['profile_yazisi'] = "alisveriz özeti ";
            $data['subview'] = 'checkout/alisveris_ozeti';
            $this->load->view('layouts/default1',$data);        
    }
    public function paypal_ile_ode()
    {
  /*     echo "<pre>";
         print_r($this->session->userdata);
         var_dump($this->session->userdata('cart_id'));*/
       $hizli_al = false;
        
        if($this->session->userdata('cart_id'))
        {
            $cart_id = $this->session->userdata('cart_id'); 
                 
        }
        else
        {
             $cart_id = $this->session->userdata('talepler_hemenal');   
             $hizli_al = true;
        }
    /*    echo $cart_id; 
       die();
       echo "<pre>";
       print_r($this->session->userdata);
       echo "</pre>";
       die(); */
        if($this->sepetim_model->check_stocks($cart_id))
        {
        	$config['business'] 			= 'admin@depoda.com';
    		$config['cpp_header_image'] 	= ''; //Image header url [750 pixels wide by 90 pixels high]
    		$config['return'] 				= base_url()."checkout/success";
    		$config['cancel_return'] 		= base_url()."checkout/fail";
    		$config['notify_url'] 			= 'process_payment.php'; //IPN Post
    		$config['production'] 			= FALSE; //Its false by default and will use sandbox
    //		$config['discount_rate_cart'] 	= 20; //This means 20% discount
    		$config["invoice"]				= time().'-'.$this->session->userdata('user_id'); //The invoice id / fatura id
    	
        	$config["lc"] = 'TR';
      //      $config["currency_code"]        = "TRY";
    		//$config["discount_amount_cart"] = '9.99'; //Discount amount [9.99]
    		//$config["discount_rate_cart"] 	= '50'; //Discount percentage [15]
     
    
        	$this->load->library('paypal',$config);

      
            if($hizli_al)
            {
                $cart_products = $this->db->where('cart_id',$cart_id)->get('cart_products');
                if($cart_products->num_rows() > 0)
                {
                    foreach($cart_products->result() as $product)
                    {
                       
                        if($this->seller_model->get_unit_price($product->quantitiy,$product->seller_id) != false)
                        {
                            $unit_price = $this->seller_model->get_unit_price($product->quantitiy,$product->seller_id);
                        }
                        $quantity = $product->quantitiy;
                        $model = $this->product_model->get_product_details($product->product_id)->row(0)->model;
                        $name  = $this->product_model->get_product_details($product->product_id)->row(0)->name;
                        $product_id = $product->product_id;
                        $this->paypal->add($model." ".$name,$unit_price,$quantity,$product_id);
                    }
                }
                else
                {
                    die("cart id ye bagli ürün bulunamadı");
                }   

            }
            else
            {
                $cart_products = $this->session->userdata('products');     
                foreach($cart_products as $products)
                {
                    $unit_price = ($products['ptotal'] / $products['quantitiy']);
                    $quantity   =  $products['quantitiy'];
                    $this->paypal->add($products['model']." ".$products['name'],$unit_price,$quantity,$products['product_id']); 
                }
            }

            $payment_info = array(
                'invoice_id'    =>  time().'-'.$this->session->userdata('user_id'),
                'user_id'       =>  $this->session->userdata('user_id'),
                'cart_id'       =>  $cart_id,
                'type'          =>  0,   // paypal = 0
                'dateadd'       =>  date("Y-m-d H:i:s"),
                'dateupd'       =>  date("Y-m-d H:i:s"),
                'adres_id'      =>  $this->session->userdata('checkout_adres_id'),
                'status'        =>  0
            );
            if($this->db->insert('payment',$payment_info))
            {
                $this->paypal->pay();    
            }
            else
            {
                echo  $this->db->_error_message();  
                die("checkout paypalile öle function payment insert hata");
            }
                        
        }
        else
        {
            $this->session->set_flashdata('errormsg','Almaya çalıştığınız ürünün stoğunda değişiklik oldu, lütfen mevcut yeni adet seçiniz.');
            redirect('cart/sepetim','refresh');
        }
		
		//$this->paypal->pay(); //Proccess the payment
    }
    public function success()
    {
        /*echo "<pre>dsfgsdfg";
        print_r($this->input->post());
        echo "</pre>";
        die();*/
        
        if($this->db->where('invoice_id',$this->input->post('invoice'))->update('payment',array('status' => 1)))
        {
           
            $this->session->set_userdata('invoice',$this->input->post('invoice'));
            if($this->db->where('cart_id',$this->session->userdata('cart_id'))->update('cart',array('status' => 0)))
            {
                //$this->paypal_info['email'] = "asdfasdf";//$this->input->post('payer_email');
                $cart_id = $this->db->where('invoice_id',$this->input->post('invoice'))->get('payment')->row(0)->cart_id;
                $buyer_id = $this->db->where('invoice_id',$this->input->post('invoice'))->get('payment')->row(0)->user_id;
                $adres_id = $this->db->where('invoice_id',$this->input->post('invoice'))->get('payment')->row(0)->adres_id;
                $cart_products = $this->db->where('cart_id',$cart_id)->get('cart_products')->result();
                foreach($cart_products as $product)
                {
                    $seller_id = $product->seller_id;
                    $seller_info = $this->db->where('seller_id',$seller_id)->get('seller')->row(0);
                    
                    $order_details = array(
                    'cart_product_id'   =>  $product->cart_product_id,
                    'invoice_id'        =>  $this->input->post('invoice'),
                    'buyer_id'          =>  $buyer_id,
                    'seller_id'         =>  $seller_info->seller_id,
                    'seller_user_id'    =>  $seller_info->user_id,
                    'cart_id'           =>  $cart_id,
                    'kargo_status'      =>  0,
                    'quantitiy'         =>  $product->quantitiy,
                    'adres_id'          =>  $adres_id,
                    'dateadd'           =>  date("Y-m-d H:i:s"),
                    'dateupd'           =>  date("Y-m-d H:i:s"),
                    );
                    if(!$this->db->insert('orders',$order_details))
                    {
                         die($this->db->_error_message);
                    }

                    
                }

                
                       // order tablosunu olustur bilgileri gir
                       
                     // notifikasyonlar
               $this->load->helper('mail_helper');
    
                if(send_mail('tunailgaz@gmail.com','Ödemeniz Onaylandı',get_urun_aldiniz_msg($cart_products)))
                {
                    
                }
                else
                {
                    
                }

                     
                     // seller tablosundan stock dan falan düşülcek
                     // seller tablosu update edilcek
               //     echo $this->seller_model->update_stock($this->session->userdata('cart_id'));
                 //    die("<br>".$this->db->last_query());
                if($this->seller_model->update_stock($cart_id))
                {
                 
                    redirect('checkout/alisveris_ozeti','refresh');
                }
                else
                {
                    die("bu hatayı almamaız lazım cCckoutLINE155/ update stock hatası");
                }
                
            }
            else
            {
                
                 die($this->db->_error_message());
            }
        
                        
        }
        else
        {
            die($this->db->_error_message());
        }


    }
    public function fail()
    {
        
        
        
       echo "<pre>";
        print_r($this->session->userdata);
        echo "</pre><hr>";
    }
    public function end_payment()
    {
        
        $invoice_id = explode("-",$this->input->post('invoice_id'));
        $invoice_id = $invoice_id[0];
        $order_id   = $this->input->post('order_id');
        $cart_product_id    =   $this->input->post('cart_product_id');
        
        if($this->db->where('order_id',$order_id)->update('orders',array('kargo_status'=>2,'status' => 2)))
        {
            // orderin parasını yatır adama
            echo "order tablosundaki order update edildi status 2 oldu";
            
           	$config['business'] 			= 'admin@depoda.com';
    		$config['cpp_header_image'] 	= ''; //Image header url [750 pixels wide by 90 pixels high]
    		$config['return'] 				= base_url()."checkout/success";
    		$config['cancel_return'] 		= base_url()."checkout/fail";
    		$config['notify_url'] 			= 'process_payment.php'; //IPN Post
    		$config['production'] 			= FALSE; //Its false by default and will use sandbox
    //		$config['discount_rate_cart'] 	= 20; //This means 20% discount
    		$config["invoice"]				= time().'-'.$this->session->userdata('user_id'); //The invoice id / fatura id
    	
        	$config["lc"] = 'TR';
      //      $config["currency_code"]        = "TRY";
    		//$config["discount_amount_cart"] = '9.99'; //Discount amount [9.99]
    		//$config["discount_rate_cart"] 	= '50'; //Discount percentage [15]
             $this->load->helper('mail_helper');
             $seller_user_id = $this->db->where('order_id',$order_id)->get('orders')->row(0)->seller_user_id;
            $seller_info = $this->user_model->get_user_details($seller_user_id)->row(0)->email;
             if(send_mail($seller_info,'Satışınız onaylandı',onaylandi_message($order_id)))
             {
                // now what..
             }
             else
             {
                die("satis onaylandı maili gitmedi");
             }
             
            
        	$this->load->library('paypal',$config);
            
            
            
           $total_invoice_num = $this->db->where(
            array('invoice_id'=>$invoice_id)
            )->get('orders')->num_rows();
            $completed_invoice_num = $this->db->where(
            array('invoice_id'=>$invoice_id,'status' => 2)
            )->get('orders')->num_rows();
            echo "tot:inv_num:".$total_invoice_num."<br>";
            echo "comp:inv_num".$completed_invoice_num."<br>";
            echo $this->input->post('invoice_id');
            if($completed_invoice_num == $total_invoice_num)
            {
                
                if($this->db->where('invoice_id',$this->input->post('invoice_id'))->update('payment',array('status' => 2)))
                {
                    // redirect successfull
                    
                    echo "payment tablosu update edildi status 2 oldu";
                }
                else
                {
                    die($this->db->_error_message());
                }
            }
            else
            {
                // redirect orderin parası verildi
            }
            
        }
        else
        {
            die($this->db->_error_message());
        }
        print_r($this->input->post());
    }
    /*public function test()
    {
        $this->config->load('paypal');
		$config = array(
			'Sandbox' => $this->config->item('Sandbox'), 			// Sandbox / testing mode option.
			'APIUsername' => $this->config->item('APIUsername'), 	// PayPal API username of the API caller
			'APIPassword' => $this->config->item('APIPassword'), 	// PayPal API password of the API caller
			'APISignature' => $this->config->item('APISignature'), 	// PayPal API signature of the API caller
			'APISubject' => '', 									// PayPal API subject (email address of 3rd party user that has granted API permission for your app)
			'APIVersion' => $this->config->item('APIVersion')		// API version you'd like to use for your call.  You can set a default version in the class and leave this blank if you want.
		);
		
		// Show Errors
		if($config['Sandbox'])
		{
			error_reporting(E_ALL);
			ini_set('display_errors', '1');
		}

	   
		$this->load->library('paypal/Paypal_pro', $config);

        $GBFields = array('returnallcurrencies' => '1');
		$PayPalRequestData = array('GBFields'=>$GBFields);
		$PayPalResult = $this->paypal_pro->GetBalance($PayPalRequestData);
		echo "<pre>";
        print_r($PayPalResult);
        echo "<br>";
		if(!$this->paypal_pro->APICallSuccessful($PayPalResult['ACK']))
		{
			$errors = array('Errors'=>$PayPalResult['ERRORS']);
			print_r($errors);
            die();
		}
		else
		{
			// Successful call.  Load view or whatever you need to do here.
			$data = array('PayPalResult'=>$PayPalResult);
			echo "succes <br>";
            print_r($data);
		}
        
    }*/
    public function mail()
    {

    $cart_products = $this->db->where('cart_id',223)->get('cart_products')->result();
   
  $this->load->helper('mail_helper');
    
                var_dump(send_mail('tunailgaz@gmail.com','this basgan is on fire',get_urun_aldiniz_msg($cart_products)));
    }
    

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */